#!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb
import re
import os
import sys

# 打开数据库连接
db = MySQLdb.connect("10.0.1.3", "oms", "HbtXN9cDy3vCbXdI", "ioms", charset='utf8' )
# 使用cursor()方法获取操作游标 
cursor = db.cursor()

deploy_ip="10.0.0.175"

def oms_monitor():
    '''
    OMS进程监控，轮询查看数据库中进程pid，若异常更新pstatus
    '''
    #清空记录文件
    f=open('/tmp/process.txt', "w+")
    f.seek(0)
    f.truncate()

    sql = "select * from process_process_im_daemon where buildenv='%s';"%(deploy_ip)
    try:
        #清空记录文件
        f=open('/tmp/oms-process.txt', "w+")
        f.seek(0)
        f.truncate()

        # 执行SQL语句
        cursor.execute(sql)
    
        # 获取所有记录列表
        results = cursor.fetchall()
        for row in results:
            pname = row[2]
            pid = os.popen("pgrep -f %s"%(pname))
            ppid = pid.readlines()
            if len(ppid) <= 0:
                ppid = "1"
                pid_error_update_sql = "update process_process_im_daemon set pstatus = '1', pid = ' ' where alias='%s' and buildenv='%s';"%(pname, deploy_ip) 
                cursor.execute(pid_error_update_sql)
                db.commit()
            else:
                for p in range(len(ppid)):
                    pid_success_update_sql = "update process_process_im_daemon set pstatus = '0', pid = '%s' where alias='%s' and buildenv='%s';"%(str(ppid[p]).strip(), pname, deploy_ip)
                    cursor.execute(pid_success_update_sql)
                    db.commit()
                    with open('/tmp/process.txt','a+') as f:
                        f.write(pname+","+str(ppid[p]).strip()+"\n")
    except Exception as e:
        print "Error: unable to fecth data"

def oms_start():
    '''
    OMS进程开启,执行start,根据pid是否为空更新数据库,返回状态码
    '''
    pass

def oms_stop():
    '''
    OMS进程关闭,执行stop,根据pid是否为空更新数据库,返回状态码
    '''
    pass

if __name__ == '__main__':
    if sys.argv[1] == "monitor":
        oms_monitor()
    elif sys.argv[1] == "start":
        print "start"
        oms_start()
    elif sys.argv[1] == "stop":
        print "stop"
        oms_stop()

    db.close()    

